import {ajaxFun} from "../../utils/ajax"
Page({


  data: {
     goodsList:[],
     page:1,
     allChecked: false,
     totalPrice:0//总价
  },
  onLoad(){
    this.getList()
  },
  onChangeItem(e) {//单机某一个
  //  sonme
    let index=e.target.dataset.index;
      let  newArry=this.data.goodsList;
      newArry[index].blo=e.detail;
      let onoff= newArry.some(item=>item.blo==false);
      console.log(onoff);

      this.setData({
        goodsList:newArry,
        allChecked:!onoff
      },()=>{
        this.allPrice()
      })
  },
async getList(){//获取数据
  let result=await ajaxFun(`/shop-cart/page`,"get",{
    pageNumber:this.data.page
  })
  if(result.resultCode==200){
    if(result.data.list.length==0){
       wx.showToast({
         title: '没有更多数据了',
         icon:"none"
       })
      return false;
    }

    // 先不要直接赋值
    result.data.list.map(item=>{
         item.blo=false
    })
    console.log(result.data.list);
    this.setData({
      goodsList:[...this.data.goodsList,...result.data.list]
    },()=>{
      this.allPrice()
    })
  }
},
async onChange(e){//加加减减
  let index=e.target.dataset.index

  let newArry=this.data.goodsList;
  newArry[index].goodsCount=e.detail;
let result=await ajaxFun("/shop-cart","put",{
  "cartItemId": this.data.goodsList[index].cartItemId,//这一项的购物车id
  "goodsCount": e.detail
})

  this.setData({
    goodsList:newArry
  },()=>{
    this.allPrice()
  })
  // console.log(this.data.goodsList);

},
onReachBottom(){ //console.log("分页");
 
  this.setData({
    page:this.data.page+1
  },()=>{
    this.getList()
  })
},
async delFun(e){//删除
  let index=e.target.dataset.index;
  let cartItemid=this.data.goodsList[index].cartItemId;
  let result=await ajaxFun(`/shop-cart/${cartItemid}`,"DELETE",{});
  if(result.resultCode==200){//后端删除
      let  newArry=this.data.goodsList;
      newArry.splice(index,1);
      this.setData({
        goodsList:newArry
      },()=>{
        this.allPrice()
      })
  }
},
onChangeAll(e){// 全选和反选
  console.log(e.detail);
  this.setData({
      allChecked:e.detail
  },()=>{
    let newArry=this.data.goodsList;
    newArry.map(item=>{
        item.blo=this.data.allChecked
    })
    this.setData({
      goodsList:newArry
    },()=>{
      this.allPrice()
    })
  })
},
allPrice(){//计算总价
   let sum=0;
   this.data.goodsList.map(item=>{
       if(item.blo){
        sum+=Number(item.sellingPrice)*Number(item.goodsCount)
       }
   })
   this.setData({
    totalPrice:sum*100
   })
},
onClickButton(){
  let cartItemIds=[];
   this.data.goodsList.map(item=>{
       if(item.blo){
           cartItemIds.push(item.cartItemId)
       }
   })
   if(cartItemIds.length>0){
      let cartItemIdsParams=JSON.stringify(cartItemIds)
      wx.navigateTo({
        url: `/orderPackage/pages/submitorder/submitorder?cartItemIds=${cartItemIdsParams}`,
})
   }else{
     wx.showToast({
       title: '请选中购买的商品',
       icon:"none"
     })
   }
 
    
}



})